<template>
  <div class="file-preview-header">
    <div class="left-actions">
      <el-button @click="$emit('back')" size="small">
        <el-icon class="mr-1"><ArrowLeft /></el-icon>
        返回
      </el-button>
      <div class="file-info">
        <!-- 一个标签 -->
        <el-tag type="info" size="small">{{ fileTypeDisplay }}</el-tag>
        <span class="file-name">{{ fileName }}</span>
      </div>
    </div>
    
    <div class="right-actions">
      <el-tooltip :content="permissionStore.canDownload ? '下载文件' : permissionStore.downloadDisabledMessage" placement="top">
        <el-button 
          type="primary" 
          size="small" 
          @click="$emit('download')"
          :disabled="!permissionStore.canDownload"
        >
          <el-icon class="mr-1"><Download /></el-icon>
          下载
        </el-button>
      </el-tooltip>
      
      <el-button type="success" size="small" @click="handleShareClick">
        <el-icon class="mr-1"><Share /></el-icon>
        分享
      </el-button>
      
      <el-button type="warning" size="small" @click="$emit('toggleFullscreen')">
        <el-icon class="mr-1">
          <FullScreen v-if="!isFullscreen" />
          <Close v-else />
        </el-icon>
        {{ isFullscreen ? '退出全屏' : '全屏' }}
      </el-button>
    </div>
    
    <!-- 分享对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="分享文件"
      width="400px"
      align-center
    >
      <div class="share-dialog-content">
        <!-- 短链接分享 -->
        <div class="short-link-section">
          <div class="section-title">分享链接</div>
          <div class="link-input-group">
            <el-input v-model="shortLink" readonly size="small">
              <template #append>
                <el-button @click="copyShortLink">复制</el-button>
              </template>
            </el-input>
          </div>
          <div class="link-description">
            <small>安全短链接，方便快捷分享</small>
          </div>
        </div>
        
        <!-- 二维码 -->
        <div class="qrcode-section">
          <div class="section-title">扫描二维码访问</div>
          <div class="qrcode-container" ref="qrcodeContainerRef">
            <!-- 二维码canvas -->
            <div class="qrcode-wrapper">
              <canvas ref="qrcodeCanvas" width="200" height="200"></canvas>
              <!-- 底部文件名 -->
              <div class="qrcode-filename">
                <span class="gradient-text">{{ displayFileName }}</span>
              </div>
            </div>
          </div>
          <!-- 复制图片按钮 -->
          <div class="qrcode-actions">
            <el-button size="small" @click="saveQRCodeImage" type="primary">
              <el-icon class="mr-1"><Download /></el-icon>
              保存图片
            </el-button>
            <el-button size="small" @click="copyQRCodeImage">
              <el-icon class="mr-1"><CopyDocument /></el-icon>
              复制图片
            </el-button>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="generateNewLink">重新生成</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Download, Share, FullScreen, Close, CopyDocument } from '@element-plus/icons-vue';
import { useFilePreviewStore, usePermissionStore } from '../../../store';
import { generateCompactLink } from '../../../utils/crypto';
import QRCode from 'qrcode';

const props = defineProps({
  fileName: {
    type: String,
    required: true
  },
  fileType: {
    type: String,
    required: true
  },
  fileUrl: {
    type: String,
    required: true
  },
  isFullscreen: {
    type: Boolean,
    default: false
  }
});

defineEmits(['back', 'download', 'toggleFullscreen']);

// 获取store
const filePreviewStore = useFilePreviewStore();
const permissionStore = usePermissionStore();

// 格式化文件类型显示
const fileTypeDisplay = computed(() => {
  const typeMap = {
    'document': '文档',
    'markdown': 'Markdown',
    'pdf': 'PDF',
    'spreadsheet': '电子表格',
    'presentation': '演示文稿',
    'image': '图片',
    'video': '视频',
    'html': 'HTML',
    'txt': '文本文件'
  };
  
  return typeMap[props.fileType] || props.fileType.toUpperCase();
});

// 文件名处理 - 去掉后缀
const displayFileName = computed(() => {
  if (!props.fileName) return '';
  
  // 移除文件扩展名
  const lastDotIndex = props.fileName.lastIndexOf('.');
  if (lastDotIndex !== -1) {
    return props.fileName.substring(0, lastDotIndex);
  }
  
  return props.fileName;
});

// 分享功能相关
const dialogVisible = ref(false);
const shortLink = ref('');
let baseUrl = window.location.origin + window.location.pathname;
const qrcodeCanvas = ref(null);
const qrcodeContainerRef = ref(null);

// 处理分享按钮点击
const handleShareClick = () => {
  dialogVisible.value = true;
  generateShortLink();
};

// 生成超短链接
const generateShortLink = async () => {
  try {
    // 准备文件信息对象
    const fileInfo = {
      url: props.fileUrl,
      name: props.fileName,
      type: props.fileType
    };
    
    // 生成超短链接
    const shortCode = generateCompactLink(fileInfo);
    if (!shortCode) {
      ElMessage.error('生成分享链接失败');
      return;
    }
    
    // 构建完整的短链接 - 适配History路由模式
    const currentUrl = new URL(window.location.href);
    shortLink.value = `${currentUrl.origin}/s/${shortCode}`;
    
    // 生成二维码
    renderQRCode();
  } catch (error) {
    console.error('生成短链接失败:', error);
    ElMessage.error('生成分享链接失败');
  }
};

// 渲染二维码
const renderQRCode = async () => {
  if (!qrcodeCanvas.value || !shortLink.value) return;
  
  try {
    console.log('渲染二维码:', shortLink.value);
    
    // 先使用标准方式生成二维码
    await QRCode.toCanvas(qrcodeCanvas.value, shortLink.value, {
      width: 200,
      margin: 1,
      color: {
        dark: '#007AFF',  // 蓝色码点
        light: '#ffffff'
      }
    });
    
    // 获取canvas上下文
    const ctx = qrcodeCanvas.value.getContext('2d');
    const canvasData = ctx.getImageData(0, 0, 200, 200);
    const data = canvasData.data;
    
    // 定位码眼的位置（左上角、右上角、左下角的大方块）
    const positionPatterns = [
      {x: 0, y: 0},      // 左上角
      {x: 0, y: 172},    // 左下角
      {x: 172, y: 0}     // 右上角
    ];
    
    // 遍历像素，修改码眼颜色
    for (let pattern of positionPatterns) {
      // 码眼大小约为7x7模块，每个模块可能有多个像素
      for (let y = 0; y < 28; y++) {
        for (let x = 0; x < 28; x++) {
          const pixelX = pattern.x + x;
          const pixelY = pattern.y + y;
          
          if (pixelX < 200 && pixelY < 200) {
            const index = (pixelY * 200 + pixelX) * 4;
            
            // 检查是否为深色像素（码点）
            if (data[index] === 0 && data[index + 1] === 122 && data[index + 2] === 255) { // 蓝色(#007AFF)
              // 将此像素改为橙色(#FF9500)
              data[index] = 255;     // R
              data[index + 1] = 149;  // G
              data[index + 2] = 0;    // B
              // Alpha 通道保持不变
            }
          }
        }
      }
    }
    
    // 将修改后的图像数据渲染回canvas
    ctx.putImageData(canvasData, 0, 0);
    
    console.log('Instagram风格二维码渲染成功');
  } catch (err) {
    console.error('生成二维码失败:', err);
    // 使用备用方法
    try {
      // 备用方法无法添加Instagram风格，只使用蓝色
      const dataUrl = await QRCode.toDataURL(shortLink.value, {
        color: {
          dark: '#007AFF',
          light: '#ffffff'
        }
      });
      const img = new Image();
      img.src = dataUrl;
      img.onload = () => {
        const ctx = qrcodeCanvas.value.getContext('2d');
        ctx.clearRect(0, 0, 200, 200);
        ctx.drawImage(img, 0, 0, 200, 200);
        console.log('备用二维码渲染成功');
      };
    } catch (fallbackErr) {
      console.error('备用二维码生成也失败:', fallbackErr);
    }
  }
};

// 生成新链接
const generateNewLink = async () => {
  await generateShortLink();
  ElMessage.success('链接已更新');
};

// 复制短链接
const copyShortLink = async () => {
  await copyToClipboard(shortLink.value);
};

// 复制到剪贴板函数
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('链接已复制到剪贴板');
  } catch (err) {
    console.error('复制失败:', err);
    
    // 回退方案
    try {
      const input = document.createElement('input');
      input.value = text;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      ElMessage.success('链接已复制到剪贴板');
    } catch (fallbackErr) {
      ElMessage.error('复制失败，请手动复制');
    }
  }
};

// 监听对话框显示状态
watch(dialogVisible, async (newVal) => {
  if (newVal) {
    // 对话框显示时，如果没有短链接则生成
    if (!shortLink.value) {
      await generateShortLink();
    } else {
      // 否则确保二维码已渲染
      await nextTick();
      renderQRCode();
    }
  }
});

// 组件挂载后初始化
onMounted(() => {
  // 确保URL处理正确
  const locationUrl = window.location;
  const originUrl = locationUrl.origin + locationUrl.pathname;
  baseUrl = originUrl;
});

// 保存二维码图片
const saveQRCodeImage = () => {
  if (!qrcodeCanvas.value) return;
  
  try {
    // 创建一个新的canvas，用于组合二维码和文件名
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const padding = 20;
    const fontSize = 16;
    
    // 设置canvas大小，考虑文字区域
    canvas.width = qrcodeCanvas.value.width + padding * 2;
    canvas.height = qrcodeCanvas.value.height + padding * 2 + fontSize * 2;
    
    // 绘制白色背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制二维码 - 直接使用已经处理过的Instagram风格二维码
    ctx.drawImage(qrcodeCanvas.value, padding, padding);
    
    // 绘制渐变文字
    const gradient = ctx.createLinearGradient(
      padding, 
      qrcodeCanvas.value.height + padding + fontSize,
      canvas.width - padding * 2, 
      qrcodeCanvas.value.height + padding + fontSize
    );
    gradient.addColorStop(0, '#007AFF');  // 蓝色
    gradient.addColorStop(1, '#FF9500');  // 橙色
    
    ctx.fillStyle = gradient;
    ctx.font = `bold ${fontSize}px Arial`;
    ctx.textAlign = 'center';
    ctx.fillText(
      displayFileName.value, 
      canvas.width / 2, 
      qrcodeCanvas.value.height + padding + fontSize
    );
    
    // 创建下载链接
    const link = document.createElement('a');
    link.download = `${displayFileName.value || '二维码'}.png`;
    link.href = canvas.toDataURL('image/png');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage.success('二维码图片已保存');
  } catch (error) {
    console.error('保存二维码图片失败:', error);
    ElMessage.error('保存失败，请重试');
  }
};

// 复制二维码图片
const copyQRCodeImage = async () => {
  if (!qrcodeCanvas.value) return;
  
  try {
    // 创建一个新的canvas，用于组合二维码和文件名
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const padding = 20;
    const fontSize = 16;
    
    // 设置canvas大小，考虑文字区域
    canvas.width = qrcodeCanvas.value.width + padding * 2;
    canvas.height = qrcodeCanvas.value.height + padding * 2 + fontSize * 2;
    
    // 绘制白色背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制二维码 - 使用已经渲染好的Instagram风格二维码
    ctx.drawImage(qrcodeCanvas.value, padding, padding);
    
    // 绘制渐变文字
    const gradient = ctx.createLinearGradient(
      padding, 
      qrcodeCanvas.value.height + padding + fontSize,
      canvas.width - padding * 2, 
      qrcodeCanvas.value.height + padding + fontSize
    );
    gradient.addColorStop(0, '#007AFF');  // 蓝色
    gradient.addColorStop(1, '#FF9500');  // 橙色
    
    ctx.fillStyle = gradient;
    ctx.font = `bold ${fontSize}px Arial`;
    ctx.textAlign = 'center';
    ctx.fillText(
      displayFileName.value, 
      canvas.width / 2, 
      qrcodeCanvas.value.height + padding + fontSize
    );
    
    // 获取canvas图像数据
    const imageData = canvas.toDataURL('image/png');
    
    // 尝试使用现代剪贴板API
    try {
      const blob = await (await fetch(imageData)).blob();
      await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
      ]);
      ElMessage.success('二维码图片已复制到剪贴板');
      return;
    } catch (clipboardError) {
      console.warn('现代剪贴板API失败，尝试备用方案:', clipboardError);
    }
    
    // 备用方案：创建一个图片元素并提示用户手动复制
    const img = document.createElement('img');
    img.src = imageData;
    img.style.position = 'fixed';
    img.style.top = '-9999px';
    document.body.appendChild(img);
    
    // 创建临时选区
    const range = document.createRange();
    range.selectNode(img);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    
    // 尝试复制
    const success = document.execCommand('copy');
    window.getSelection().removeAllRanges();
    document.body.removeChild(img);
    
    if (success) {
      ElMessage.success('二维码图片已复制到剪贴板');
    } else {
      ElMessage.warning('无法自动复制，请右键图片手动复制');
    }
  } catch (error) {
    console.error('复制二维码图片失败:', error);
    ElMessage.error('复制失败，请重试');
  }
};
</script>

<style scoped>
.file-preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1rem;
  background-color: white;
  border-bottom: 1px solid #e5e7eb;
  z-index: 10;
}

.left-actions, .right-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mr-1 {
  margin-right: 4px;
}

.file-info {
  margin-left: 1rem;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.file-name {
  font-weight: 500;
  font-size: 1rem;
  max-width: 70vw;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-type {
  font-size: 0.75rem;
  color: #6b7280;
  text-transform: uppercase;
}

/* 分享对话框样式 */
.share-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.section-title {
  font-weight: 500;
  font-size: 0.9rem;
  color: #374151;
  margin-bottom: 0.75rem;
}

.link-input-group {
  margin-bottom: 0.5rem;
}

.link-description {
  font-size: 0.75rem;
  color: #6b7280;
  margin-top: 0.25rem;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  margin: 0.5rem 0;
}

.qrcode-wrapper {
  position: relative;
  display: inline-block;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e5e7eb;
}

.qrcode-filename {
  position: relative;
  margin-top: 10px;
  text-align: center;
  padding: 6px 0;
  font-weight: bold;
}

.gradient-text {
  background: linear-gradient(135deg, #007AFF, #FF9500);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  color: transparent;
  font-weight: 600;
  font-size: 16px;
  padding: 0 8px;
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.qrcode-actions {
  display: flex;
  justify-content: center;
  gap: 0.75rem;
  margin-top: 0.75rem;
}

.qrcode-actions .el-button {
  border-radius: 20px;
  padding-left: 16px;
  padding-right: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 1rem;
}

/* 高亮短链接区域 */
.short-link-section {
  background-color: #f0f9ff;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #bae6fd;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .file-preview-header {
    padding: 0.5rem;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .right-actions {
    margin-top: 0.5rem;
    width: 100%;
    justify-content: space-between;
  }
  
  .file-name {
    max-width: 150px;
    font-size: 0.85rem;
  }
  
  .file-type {
    font-size: 0.7rem;
  }
}
</style> 